package XMLReader;

public class XMLParser
{
    private XMLTree tree=null;
    public XMLParser()
    {
        this.tree = new XMLTree();
    }
    public void parse (String line) 
    {
        line = line.trim();
        if (line.isEmpty()) return;
        String allparts[] = line.split("[<, ,?,>]");
        String nonemptyparts[] = new String[allparts.length];
        int i = 0, j = 0;
        for (; i < allparts.length; i++)
            if (!allparts[i].isEmpty())
                nonemptyparts[j++] = allparts[i];
        for (i = j; i < nonemptyparts.length; i++) 
            nonemptyparts[i] = "";
        Boolean endtag = false;
        if (line.endsWith(">")) {
            if (nonemptyparts[j-1].equalsIgnoreCase("/"+nonemptyparts[0]) ||line.startsWith("</"))
            { // ) {
                endtag = true;
                nonemptyparts[j] = nonemptyparts[0];
                --j;
            }
        }
        i = 0;
        Boolean starttag = (line.startsWith("<") && !line.startsWith("</"));
        if (starttag) 
            tree.addleaf(new XMLEntry(nonemptyparts[i++]));
        String content = starttag ? "" : nonemptyparts[0];
        for (; i < j; i++) 
            content += " "+nonemptyparts[i];
        content = content.trim();
        if (content.startsWith("/")) 
            content = "";
        if (!content.isEmpty()) 
            tree.content((tree.content()+" "+content).trim());

        if (endtag || (line.startsWith("<?") && line.endsWith("?>")))
            tree.downstream();
    }
	
    public XMLTree getTree() 
    {
        return tree;
    }

    public void transverse() 
    {
        tree.walk();
    }

}
